%this function identifies wrong fields and deletes them
%Created by Ricardo Mejia-Alvarez.
%University of Illinois at Urbana-Champaign
%Urbana, IL. 12/20/09

%U : any vector field from the same .vec file. For instance, it can be one 
%of the velocity coordinates or the velocity magnitude

%threshold : threshold for depuration


%wrong = 1 : the vector field is discarded
%wrong = 0 : the vector field is not discarded

%modified:  04/18/2010


function [wrong] = depurationResiduals(threshold,path,pathJunk,varargin)
PercentageTolerance = 0.02; %this tolerance defines levels or error to tolerate

for k = 1 : length(varargin)
    U = cell2mat( varargin(k) );
    m = size(U);
    med = median(U,2);
    Umed = repmat(med,[1,m(2)]);  

    residualsU = U - Umed;           %finding residuals of matrix U

    iqrR = iqr(residualsU');         %finding the interquartil range of the 
                                     %residuals of matrix U as a measure of
                                     %dispersion

    iqrRU = repmat(iqrR',[1,m(2)]);                                   


    NormResiduals = residualsU ./ iqrRU ;    %normalizing residuals by
                                             %the interquartile range 

    NormResiduals = reshape(NormResiduals,numel(NormResiduals),1);



    test = find( abs( NormResiduals ) > threshold );


    if isempty(test) == 1
        wrong = 0;
    else
        if numel(test) / numel(NormResiduals) > PercentageTolerance
            wrong = 1;
            movefile(path,pathJunk);
            break
        else
            wrong = 0;
        end

    end
    
end

 end %end of the function
